import { THEME } from '@/utils/constant';
import { defineStore } from 'pinia';
import { onMounted, ref, watch } from 'vue';

const DEFAULT_THEME = {
  primary: '#409eff',
  text: '#303133',
  background: '#f6f6f6',
  showRefresh: true,
  showLock: true,
  showSearch: true,
  showMessage: true,
  showSize: true,
  showIn18: true,
  showTabs: true,
  isComic: false
};

export const useThemeStore = defineStore('theme', () => {
  let recordTheme = JSON.parse(localStorage.getItem(THEME));

  const theme = ref(Object.assign(JSON.parse(JSON.stringify(DEFAULT_THEME)), recordTheme));

  function save() {
    localStorage.setItem(THEME, JSON.stringify(theme.value));
  }

  function reset() {
    theme.value = JSON.parse(JSON.stringify(DEFAULT_THEME));
    save();
  }

  function setComicTheme() {
    const { primary, text, background } = theme.value!;

    document.documentElement.style.setProperty('--el-color-primary', primary);
    document.documentElement.style.setProperty('--el-text-color-primary', text);
    document.documentElement.style.setProperty('--admin-bgcolor', background);

    setComic();
  }
  function setComic() {
    if (theme.value.isComic) {
      document.documentElement.style.setProperty('--el-color-primary', '#333333');
      document.documentElement.style.setProperty('--el-font-family', 'Comic Font');
      document.body.style.setProperty('font-family', 'Comic Font');
    } else {
      document.documentElement.style.setProperty('--el-color-primary', theme.value.primary);
      document.documentElement.style.removeProperty('--el-font-family');
      document.body.style.removeProperty('font-family');
    }
  }

  watch(
    [() => theme.value.primary, () => theme.value.text, () => theme.value.background],
    () => {
      setComicTheme();
    },
    { deep: true }
  );

  watch(
    () => theme.value.isComic,
    () => {
      setComic();
    }
  );

  onMounted(() => {
    setComicTheme();
  });

  return {
    theme,
    save,
    reset
  };
});
